home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 2010 April / PCWorld0410.iso / hity wydania / Ubuntu 9.10 PL / karmelkowy-koliberek-desktop-9.10-i386-PL.iso / casper / filesystem.squashfs / usr / share / hplip / base / device.pyc (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2009-10-28  |  63.4 KB  |  2,251 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. import socket
  5. import re
  6. import gzip
  7. import os.path as os
  8. import time
  9. import urllib
  10. import StringIO
  11. import httplib
  12. import struct
  13. from g import *
  14. from codes import *
  15. import utils
  16. import status
  17. import pml
  18. from prnt import pcl, ldl, cups
  19. import models
  20. import mdns
  21. import slp
  22. from strings import StringTable
  23.  
  24. try:
  25.     import hpmudext
  26. except ImportError:
  27.     if not os.getenv('HPLIP_BUILD'):
  28.         log.error('HPMUDEXT could not be loaded. Please check HPLIP installation.')
  29.         sys.exit(1)
  30.     
  31. except:
  32.     not os.getenv('HPLIP_BUILD')
  33.  
  34.  
  35. try:
  36.     MAX_BUFFER = hpmudext.HPMUD_BUFFER_SIZE
  37. except AttributeError:
  38.     MAX_BUFFER = 8192
  39.  
  40. dbus_avail = False
  41. dbus_disabled = False
  42.  
  43. try:
  44.     import dbus
  45.     from dbus import lowlevel, SessionBus
  46.     dbus_avail = True
  47. except ImportError:
  48.     log.warn('python-dbus not installed.')
  49.  
  50. import warnings
  51. warnings.simplefilter('ignore', DeprecationWarning)
  52. DEFAULT_PROBE_BUS = [
  53.     'usb',
  54.     'par',
  55.     'cups']
  56. VALID_BUSES = ('par', 'net', 'cups', 'usb')
  57. VALID_BUSES_WO_CUPS = ('par', 'net', 'usb')
  58. DEFAULT_FILTER = None
  59. VALID_FILTERS = ('print', 'scan', 'fax', 'pcard', 'copy')
  60. DEFAULT_BE_FILTER = ('hp',)
  61. pat_deviceuri = re.compile('(.*):/(.*?)/(\\S*?)\\?(?:serial=(\\S*)|device=(\\S*)|ip=(\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}[^&]*)|zc=(\\S+))(?:&port=(\\d))?', re.IGNORECASE)
  62. http_pat_url = re.compile('/(.*?)/(\\S*?)\\?(?:serial=(\\S*)|device=(\\S*))&loc=(\\S*)', re.IGNORECASE)
  63. direct_pat = re.compile('direct (.*?) "(.*?)" "(.*?)" "(.*?)"', re.IGNORECASE)
  64. pat_dynamic_ctr = re.compile('CTR:\\d*\\s.*;', re.IGNORECASE)
  65. model_dat = models.ModelData()
  66. ip_pat = re.compile('\\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\b', re.IGNORECASE)
  67. dev_pat = re.compile('/dev/.+', re.IGNORECASE)
  68. usb_pat = re.compile('(\\d+):(\\d+)', re.IGNORECASE)
  69.  
  70. class Event(object):
  71.     
  72.     def __init__(self, device_uri, printer_name, event_code, username = prop.username, job_id = 0, title = '', timedate = 0):
  73.         self.device_uri = unicode(utils.xrstrip(device_uri, '\x00'))[:64].encode('utf-8')
  74.         self.printer_name = unicode(utils.xrstrip(printer_name, '\x00'))[:64].encode('utf-8')
  75.         self.event_code = int(event_code)
  76.         self.username = unicode(utils.xrstrip(username, '\x00'))[:32].encode('utf-8')
  77.         self.job_id = int(job_id)
  78.         self.title = unicode(utils.xrstrip(title, '\x00'))[:64].encode('utf-8')
  79.         if timedate:
  80.             self.timedate = float(timedate)
  81.         else:
  82.             self.timedate = time.time()
  83.         self.pipe_fmt = '64s64sI32sI64sf'
  84.         self.dbus_fmt = 'ssisisd'
  85.  
  86.     
  87.     def debug(self):
  88.         log.debug('    device_uri=%s' % self.device_uri)
  89.         log.debug('    printer_name=%s' % self.printer_name)
  90.         log.debug('    event_code=%d' % self.event_code)
  91.         log.debug('    username=%s' % self.username)
  92.         log.debug('    job_id=%d' % self.job_id)
  93.         log.debug('    title=%s' % self.title)
  94.         log.debug('    timedate=%s' % self.timedate)
  95.  
  96.     
  97.     def pack_for_pipe(self):
  98.         return struct.pack(self.pipe_fmt, self.device_uri, self.printer_name, self.event_code, self.username, self.job_id, self.title, self.timedate)
  99.  
  100.     
  101.     def send_via_pipe(self, fd, recipient = 'hpssd'):
  102.         if fd is not None:
  103.             log.debug('Sending event %d to %s (via pipe %d)...' % (self.event_code, recipient, fd))
  104.             
  105.             try:
  106.                 os.write(fd, self.pack_for_pipe())
  107.                 return True
  108.             except OSError:
  109.                 log.debug('Failed.')
  110.                 return False
  111.             
  112.  
  113.         None<EXCEPTION MATCH>OSError
  114.  
  115.     
  116.     def send_via_dbus(self, session_bus, interface = 'com.hplip.StatusService'):
  117.         if session_bus is not None and dbus_avail:
  118.             log.debug('Sending event %d to %s (via dbus)...' % (self.event_code, interface))
  119.             msg = lowlevel.SignalMessage('/', interface, 'Event')
  120.             msg.append(signature = self.dbus_fmt, *self.as_tuple())
  121.             session_bus.send_message(msg)
  122.         
  123.  
  124.     
  125.     def copy(self):
  126.         return Event(*self.as_tuple())
  127.  
  128.     
  129.     def __str__(self):
  130.         return "<Event('%s', '%s', %d, '%s', %d, '%s', %f)>" % self.as_tuple()
  131.  
  132.     
  133.     def as_tuple(self):
  134.         return (self.device_uri, self.printer_name, self.event_code, self.username, self.job_id, self.title, self.timedate)
  135.  
  136.  
  137.  
  138. class FaxEvent(Event):
  139.     
  140.     def __init__(self, temp_file, event):
  141.         Event.__init__(self, *event.as_tuple())
  142.         self.temp_file = temp_file
  143.         self.pipe_fmt = '64s64sI32sI64sfs'
  144.         self.dbus_fmt = 'ssisisfs'
  145.  
  146.     
  147.     def debug(self):
  148.         log.debug('FAX:')
  149.         Event.debug(self)
  150.         log.debug('    temp_file=%s' % self.temp_file)
  151.  
  152.     
  153.     def __str__(self):
  154.         return "<FaxEvent('%s', '%s', %d, '%s', %d, '%s', %f, '%s')>" % self.as_tuple()
  155.  
  156.     
  157.     def as_tuple(self):
  158.         return (self.device_uri, self.printer_name, self.event_code, self.username, self.job_id, self.title, self.timedate, self.temp_file)
  159.  
  160.  
  161.  
  162. class DeviceIOEvent(Event):
  163.     
  164.     def __init__(self, bytes_written, event):
  165.         Event.__init__(self, *event.as_tuple())
  166.         self.bytes_written = bytes_written
  167.         self.pipe_fmt = '64s64sI32sI64sfI'
  168.         self.dbus_fmt = 'ssisisfi'
  169.  
  170.     
  171.     def debug(self):
  172.         log.debug('DEVIO:')
  173.         Event.debug(self)
  174.         log.debug('    bytes_written=%d' % self.bytes_written)
  175.  
  176.     
  177.     def __str__(self):
  178.         return "<DeviceIOEvent('%s', '%s', %d, '%s', %d, '%s', %f, '%d')>" % self.as_tuple()
  179.  
  180.     
  181.     def as_tuple(self):
  182.         return (self.device_uri, self.printer_name, self.event_code, self.username, self.job_id, self.title, self.timedate, self.bytes_written)
  183.  
  184.  
  185.  
  186. def init_dbus(dbus_loop = None):
  187.     global dbus_avail, dbus_avail, dbus_avail, dbus_avail, dbus_avail
  188.     service = None
  189.     session_bus = None
  190.     if not prop.gui_build:
  191.         dbus_avail = False
  192.         return (dbus_avail, None, None)
  193.     if dbus_avail and not dbus_disabled:
  194.         if os.getuid() == 0:
  195.             log.debug('Not starting dbus: running as root.')
  196.             dbus_avail = False
  197.             return (dbus_avail, None, None)
  198.         
  199.         try:
  200.             if dbus_loop is None:
  201.                 session_bus = dbus.SessionBus()
  202.             else:
  203.                 session_bus = dbus.SessionBus(dbus_loop)
  204.         except dbus.exceptions.DBusException:
  205.             os.getuid() == 0
  206.             e = os.getuid() == 0
  207.             prop.gui_build
  208.             if os.getuid() != 0:
  209.                 log.error('Unable to connect to dbus session bus.')
  210.             else:
  211.                 log.debug('Unable to connect to dbus session bus (running as root?)')
  212.             dbus_avail = False
  213.             return (dbus_avail, None, None)
  214.  
  215.         
  216.         try:
  217.             log.debug('Connecting to com.hplip.StatusService (try #1)...')
  218.             service = session_bus.get_object('com.hplip.StatusService', '/com/hplip/StatusService')
  219.             dbus_avail = True
  220.         except dbus.exceptions.DBusException:
  221.             os.getuid() == 0
  222.             e = os.getuid() == 0
  223.             prop.gui_build
  224.             
  225.             try:
  226.                 os.waitpid(-1, os.WNOHANG)
  227.             except OSError:
  228.                 pass
  229.  
  230.             path = utils.which('hp-systray')
  231.             log.debug('Running hp-systray: %s --force-startup' % path)
  232.             os.spawnlp(os.P_NOWAIT, path, 'hp-systray', '--force-startup')
  233.             log.debug('Waiting for hp-systray to start...')
  234.             time.sleep(1)
  235.             t = 2
  236.             while True:
  237.                 
  238.                 try:
  239.                     log.debug('Connecting to com.hplip.StatusService (try #%d)...' % t)
  240.                     service = session_bus.get_object('com.hplip.StatusService', '/com/hplip/StatusService')
  241.                 except dbus.exceptions.DBusException:
  242.                     None if path else os.path.exists(path)
  243.                     e = None if path else os.path.exists(path)
  244.                     log.debug('Unable to connect to dbus. Is hp-systray running?')
  245.                     t += 1
  246.                     if t > 5:
  247.                         log.warn('Unable to connect to dbus. Is hp-systray running?')
  248.                         return (False, None, None)
  249.                     time.sleep(1)
  250.                     continue
  251.                     t > 5
  252.  
  253.                 log.debug('Connected.')
  254.                 dbus_avail = True
  255.                 break
  256.                 continue
  257.                 None if path else os.path.exists(path)
  258.         except:
  259.             os.getuid() == 0<EXCEPTION MATCH>dbus.exceptions.DBusException
  260.         
  261.  
  262.     os.getuid() == 0
  263.     return (dbus_avail, service, session_bus)
  264.  
  265.  
  266. def makeURI(param, port = 1):
  267.     (cups_uri, sane_uri, fax_uri) = ('', '', '')
  268.     found = False
  269.     if dev_pat.search(param) is not None:
  270.         log.debug('Trying parallel with %s' % param)
  271.         (result_code, uri) = hpmudext.make_par_uri(param)
  272.         if result_code == hpmudext.HPMUD_R_OK and uri:
  273.             log.debug('Found: %s' % uri)
  274.             found = True
  275.             cups_uri = uri
  276.         else:
  277.             log.debug('Not found.')
  278.     elif usb_pat.search(param) is not None:
  279.         match_obj = usb_pat.search(param)
  280.         usb_bus_id = match_obj.group(1)
  281.         usb_dev_id = match_obj.group(2)
  282.         log.debug('Trying USB with bus=%s dev=%s...' % (usb_bus_id, usb_dev_id))
  283.         (result_code, uri) = hpmudext.make_usb_uri(usb_bus_id, usb_dev_id)
  284.         if result_code == ERROR_SUCCESS and uri:
  285.             log.debug('Found: %s' % uri)
  286.             found = True
  287.             cups_uri = uri
  288.         else:
  289.             log.debug('Not found.')
  290.     elif ip_pat.search(param) is not None:
  291.         log.debug('Trying IP address %s' % param)
  292.         (result_code, uri) = hpmudext.make_net_uri(param, port)
  293.         if result_code == hpmudext.HPMUD_R_OK and uri:
  294.             log.debug('Found: %s' % uri)
  295.             found = True
  296.             cups_uri = uri
  297.         else:
  298.             log.debug('Not found.')
  299.     else:
  300.         log.debug('Trying ZC hostname %s' % param)
  301.         (result_code, uri) = hpmudext.make_zc_uri(param, port)
  302.         if result_code == hpmudext.HPMUD_R_OK and uri:
  303.             log.debug('Found: %s' % uri)
  304.             found = True
  305.             cups_uri = uri
  306.         else:
  307.             log.debug('Not found.')
  308.     if not found:
  309.         log.debug('Trying serial number %s' % param)
  310.         devices = probeDevices(bus = [
  311.             'usb',
  312.             'par'])
  313.         for d in devices:
  314.             log.debug(d)
  315.             
  316.             try:
  317.                 (back_end, is_hp, bus, model, serial, dev_file, host, zc, port) = parseDeviceURI(d)
  318.             except Error:
  319.                 continue
  320.  
  321.             if bus == 'par':
  322.                 mq = queryModelByURI(d)
  323.                 (result_code, device_id) = hpmudext.device_open(d, mq.get('io-mode', hpmudext.HPMUD_UNI_MODE))
  324.                 if result_code == hpmudext.HPMUD_R_OK:
  325.                     (result_code, data) = hpmudext.get_device_id(device_id)
  326.                     serial = parseDeviceID(data).get('SN', '')
  327.                     hpmudext.close_device(device_id)
  328.                 
  329.             
  330.             if serial.lower() == param.lower():
  331.                 log.debug('Found: %s' % d)
  332.                 found = True
  333.                 cups_uri = d
  334.                 break
  335.                 continue
  336.             log.debug('Not found.')
  337.         
  338.     
  339.     if found:
  340.         
  341.         try:
  342.             mq = queryModelByURI(cups_uri)
  343.         except Error:
  344.             e = None
  345.             log.error('Error: %s' % e.msg)
  346.             (cups_uri, sane_uri, fax_uri) = ('', '', '')
  347.  
  348.         if mq.get('support-type', SUPPORT_TYPE_NONE) > SUPPORT_TYPE_NONE:
  349.             if mq.get('scan-type', 0):
  350.                 sane_uri = cups_uri.replace('hp:', 'hpaio:')
  351.             
  352.             if mq.get('fax-type', 0):
  353.                 fax_uri = cups_uri.replace('hp:', 'hpfax:')
  354.             
  355.         else:
  356.             (cups_uri, sane_uri, fax_uri) = ('', '', '')
  357.     else:
  358.         (scan_uri, fax_uri) = ('', '')
  359.     if cups_uri:
  360.         user_conf.set('last_used', 'device_uri', cups_uri)
  361.     
  362.     return (cups_uri, sane_uri, fax_uri)
  363.  
  364.  
  365. def queryModelByModel(model):
  366.     model = models.normalizeModelName(model).lower()
  367.     return model_dat[model]
  368.  
  369.  
  370. def queryModelByURI(device_uri):
  371.     
  372.     try:
  373.         (back_end, is_hp, bus, model, serial, dev_file, host, zc, port) = parseDeviceURI(device_uri)
  374.     except Error:
  375.         raise Error(ERROR_INVALID_DEVICE_URI)
  376.  
  377.     return queryModelByModel(model)
  378.  
  379.  
  380. def probeDevices(bus = DEFAULT_PROBE_BUS, timeout = 10, ttl = 4, filter = DEFAULT_FILTER, search = '', net_search = 'mdns', back_end_filter = ('hp',)):
  381.     num_devices = 0
  382.     ret_devices = { }
  383.     if search:
  384.         
  385.         try:
  386.             search_pat = re.compile(search, re.IGNORECASE)
  387.         log.error('Invalid search pattern. Search uses standard regular expressions. For more info, see: http://www.amk.ca/python/howto/regex/')
  388.         search = ''
  389.  
  390.     
  391.     for b in bus:
  392.         log.debug('Probing bus: %s' % b)
  393.         if b not in VALID_BUSES:
  394.             log.error('Invalid bus: %s' % b)
  395.             continue
  396.         
  397.         if b == 'net':
  398.             if net_search == 'slp':
  399.                 
  400.                 try:
  401.                     detected_devices = slp.detectNetworkDevices(ttl, timeout)
  402.                 except Error:
  403.                     socket.error = None
  404.                     log.error('An error occured during network probe.')
  405.                     raise ERROR_INTERNAL
  406.                 except:
  407.                     None<EXCEPTION MATCH>Error
  408.                 
  409.  
  410.             None<EXCEPTION MATCH>Error
  411.             
  412.             try:
  413.                 detected_devices = mdns.detectNetworkDevices(ttl, timeout)
  414.             except Error:
  415.                 socket.error = None
  416.                 log.error('An error occured during network probe.')
  417.                 raise ERROR_INTERNAL
  418.  
  419.             for ip in detected_devices:
  420.                 update_spinner()
  421.                 hn = detected_devices[ip].get('hn', '?UNKNOWN?')
  422.                 num_devices_on_jd = detected_devices[ip].get('num_devices', 0)
  423.                 num_ports_on_jd = detected_devices[ip].get('num_ports', 1)
  424.                 if num_devices_on_jd > 0:
  425.                     for port in range(num_ports_on_jd):
  426.                         dev = detected_devices[ip].get('device%d' % (port + 1), '0')
  427.                         if dev is not None and dev != '0':
  428.                             device_id = parseDeviceID(dev)
  429.                             model = models.normalizeModelName(device_id.get('MDL', '?UNKNOWN?'))
  430.                             if num_ports_on_jd == 1:
  431.                                 if net_search == 'slp':
  432.                                     device_uri = 'hp:/net/%s?ip=%s' % (model, ip)
  433.                                 else:
  434.                                     device_uri = 'hp:/net/%s?zc=%s' % (model, hn)
  435.                             elif net_search == 'slp':
  436.                                 device_uri = 'hp:/net/%s?ip=%s&port=%d' % (model, ip, port + 1)
  437.                             else:
  438.                                 device_uri = 'hp:/net/%s?zc=%s&port=%d' % (model, hn, port + 1)
  439.                             include = True
  440.                             mq = queryModelByModel(model)
  441.                             if not mq:
  442.                                 log.debug('Not found.')
  443.                                 include = False
  444.                             elif int(mq.get('support-type', SUPPORT_TYPE_NONE)) == SUPPORT_TYPE_NONE:
  445.                                 log.debug('Not supported.')
  446.                                 include = False
  447.                             elif filter not in (None, 'print', 'print-type'):
  448.                                 include = __checkFilter(filter, mq)
  449.                             
  450.                             if include:
  451.                                 ret_devices[device_uri] = (model, model, hn)
  452.                             
  453.                         include
  454.                     
  455.             
  456.         if b in ('usb', 'par'):
  457.             if b == 'par':
  458.                 bn = hpmudext.HPMUD_BUS_PARALLEL
  459.             else:
  460.                 bn = hpmudext.HPMUD_BUS_USB
  461.             (result_code, data) = hpmudext.probe_devices(bn)
  462.             if result_code == hpmudext.HPMUD_R_OK:
  463.                 for x in data.splitlines():
  464.                     m = direct_pat.match(x)
  465.                     if not m.group(1):
  466.                         pass
  467.                     uri = ''
  468.                     if not m.group(2):
  469.                         pass
  470.                     mdl = ''
  471.                     if not m.group(3):
  472.                         pass
  473.                     desc = ''
  474.                     if not m.group(4):
  475.                         pass
  476.                     devid = ''
  477.                     log.debug(uri)
  478.                     
  479.                     try:
  480.                         (back_end, is_hp, bb, model, serial, dev_file, host, zc, port) = parseDeviceURI(uri)
  481.                     except Error:
  482.                         continue
  483.  
  484.                     include = True
  485.                     if mdl and uri and is_hp:
  486.                         mq = queryModelByModel(model)
  487.                         if not mq:
  488.                             log.debug('Not found.')
  489.                             include = False
  490.                         elif int(mq.get('support-type', SUPPORT_TYPE_NONE)) == SUPPORT_TYPE_NONE:
  491.                             log.debug('Not supported.')
  492.                             include = False
  493.                         elif filter not in (None, 'print', 'print-type'):
  494.                             include = __checkFilter(filter, mq)
  495.                         
  496.                         if include:
  497.                             ret_devices[uri] = (mdl, desc, devid)
  498.                         
  499.                     include
  500.                 
  501.             
  502.         result_code == hpmudext.HPMUD_R_OK
  503.         if b == 'cups':
  504.             cups_printers = cups.getPrinters()
  505.             x = len(cups_printers)
  506.             for p in cups_printers:
  507.                 device_uri = p.device_uri
  508.                 log.debug('%s: %s' % (device_uri, p.name))
  509.                 if device_uri != '':
  510.                     
  511.                     try:
  512.                         (back_end, is_hp, bs, model, serial, dev_file, host, zc, port) = parseDeviceURI(device_uri)
  513.                     except Error:
  514.                         log.debug('Unrecognized URI: %s' % device_uri)
  515.                         continue
  516.  
  517.                     if not is_hp:
  518.                         continue
  519.                     
  520.                     include = True
  521.                     mq = queryModelByModel(model)
  522.                     if not mq:
  523.                         include = False
  524.                         log.debug('Not found.')
  525.                     elif int(mq.get('support-type', SUPPORT_TYPE_NONE)) == SUPPORT_TYPE_NONE:
  526.                         log.debug('Not supported.')
  527.                         include = False
  528.                     elif filter not in (None, 'print', 'print-type'):
  529.                         include = __checkFilter(filter, mq)
  530.                     
  531.                     if include:
  532.                         ret_devices[device_uri] = (model, model, '')
  533.                     
  534.                 include
  535.             
  536.     
  537.     probed_devices = { }
  538.     for uri in ret_devices:
  539.         num_devices += 1
  540.         (mdl, model, devid_or_hn) = ret_devices[uri]
  541.         include = True
  542.         if search:
  543.             match_obj = search_pat.search('%s %s %s %s' % (mdl, model, devid_or_hn, uri))
  544.             if match_obj is None:
  545.                 log.debug("%s %s %s %s: Does not match search '%s'." % (mdl, model, devid_or_hn, uri, search))
  546.                 include = False
  547.             
  548.         
  549.         if include:
  550.             probed_devices[uri] = ret_devices[uri]
  551.             continue
  552.     
  553.     cleanup_spinner()
  554.     return probed_devices
  555.  
  556.  
  557. def getSupportedCUPSDevices(back_end_filter = [
  558.     'hp'], filter = DEFAULT_FILTER):
  559.     devices = { }
  560.     printers = cups.getPrinters()
  561.     for p in printers:
  562.         
  563.         try:
  564.             (back_end, is_hp, bus, model, serial, dev_file, host, zc, port) = parseDeviceURI(p.device_uri)
  565.         except Error:
  566.             continue
  567.  
  568.         if (back_end_filter == '*' and back_end in back_end_filter or 'hpaio' in back_end_filter or back_end == 'hp') and model and is_hp:
  569.             include = True
  570.             mq = queryModelByModel(model)
  571.             if not mq:
  572.                 log.debug('Not found.')
  573.                 include = False
  574.             elif int(mq.get('support-type', SUPPORT_TYPE_NONE)) == SUPPORT_TYPE_NONE:
  575.                 log.debug('Not supported.')
  576.                 include = False
  577.             elif filter not in (None, 'print', 'print-type'):
  578.                 include = __checkFilter(filter, mq)
  579.             
  580.             if include:
  581.                 if 'hpaio' in back_end_filter:
  582.                     d = p.device_uri.replace('hp:', 'hpaio:')
  583.                 else:
  584.                     d = p.device_uri
  585.                 
  586.                 try:
  587.                     devices[d]
  588.                 except KeyError:
  589.                     devices[d] = [
  590.                         p.name]
  591.  
  592.                 devices[d].append(p.name)
  593.             
  594.         include
  595.     
  596.     return devices
  597.  
  598.  
  599. def getSupportedCUPSPrinters(back_end_filter = [
  600.     'hp'], filter = DEFAULT_FILTER):
  601.     printer_list = []
  602.     printers = cups.getPrinters()
  603.     for p in printers:
  604.         
  605.         try:
  606.             (back_end, is_hp, bus, model, serial, dev_file, host, zc, port) = parseDeviceURI(p.device_uri)
  607.         except Error:
  608.             continue
  609.  
  610.         if (back_end_filter == '*' or back_end in back_end_filter) and model and is_hp:
  611.             include = True
  612.             mq = queryModelByModel(model)
  613.             if not mq:
  614.                 log.debug('Not found.')
  615.                 include = False
  616.             elif int(mq.get('support-type', SUPPORT_TYPE_NONE)) == SUPPORT_TYPE_NONE:
  617.                 log.debug('Not supported.')
  618.                 include = False
  619.             elif filter not in (None, 'print', 'print-type'):
  620.                 include = __checkFilter(filter, mq)
  621.             
  622.             if include:
  623.                 p.name = p.name.decode('utf-8')
  624.                 printer_list.append(p)
  625.             
  626.         include
  627.     
  628.     return printer_list
  629.  
  630.  
  631. def getSupportedCUPSPrinterNames(back_end_filter = [
  632.     'hp'], filter = DEFAULT_FILTER):
  633.     printers = getSupportedCUPSPrinters(back_end_filter, filter)
  634.     return [ p.name for p in printers ]
  635.  
  636.  
  637. def getDeviceURIByPrinterName(printer_name, scan_uri_flag = False):
  638.     if printer_name is None:
  639.         return None
  640.     device_uri = None
  641.     printers = cups.getPrinters()
  642.     for p in printers:
  643.         
  644.         try:
  645.             (back_end, is_hp, bus, model, serial, dev_file, host, zc, port) = parseDeviceURI(p.device_uri)
  646.         except Error:
  647.             printer_name is None
  648.             printer_name is None
  649.             continue
  650.         except:
  651.             printer_name is None
  652.  
  653.         if is_hp and p.name == printer_name:
  654.             if scan_uri_flag:
  655.                 device_uri = p.device_uri.replace('hp:', 'hpaio:')
  656.             else:
  657.                 device_uri = p.device_uri
  658.             break
  659.             continue
  660.     
  661.     return device_uri
  662.  
  663.  
  664. def parseDeviceID(device_id):
  665.     d = { }
  666.     x = _[1]
  667.     for z in x:
  668.         y = z.split(':')
  669.         
  670.         try:
  671.             d.setdefault(y[0].strip(), y[1])
  672.         continue
  673.         except IndexError:
  674.             []
  675.             []
  676.             []
  677.             d.setdefault(y[0].strip(), None)
  678.             continue
  679.         
  680.  
  681.     
  682.     d.setdefault('MDL', '')
  683.     d.setdefault('SN', '')
  684.     if 'SERIAL' in d:
  685.         d['SN'] = d['SERIAL']
  686.         del d['SERIAL']
  687.     elif 'SERN' in d:
  688.         d['SN'] = d['SERN']
  689.         del d['SERN']
  690.     
  691.     if d['SN'].startswith('X'):
  692.         d['SN'] = ''
  693.     
  694.     return d
  695.  
  696.  
  697. def parseDynamicCounter(ctr_field, convert_to_int = True):
  698.     (counter, value) = ctr_field.split(' ')
  699.     
  700.     try:
  701.         if not utils.xlstrip(str(counter), '0'):
  702.             pass
  703.         counter = int('0')
  704.         if convert_to_int:
  705.             if not utils.xlstrip(str(value), '0'):
  706.                 pass
  707.             value = int('0')
  708.     except ValueError:
  709.         if convert_to_int:
  710.             (counter, value) = (0, 0)
  711.         else:
  712.             (counter, value) = (0, '')
  713.     except:
  714.         convert_to_int
  715.  
  716.     return (counter, value)
  717.  
  718.  
  719. def parseDeviceURI(device_uri):
  720.     m = pat_deviceuri.match(device_uri)
  721.     if m is None:
  722.         log.debug('Device URI %s is invalid/unknown' % device_uri)
  723.         raise Error(ERROR_INVALID_DEVICE_URI)
  724.     m is None
  725.     if not m.group(1).lower():
  726.         pass
  727.     back_end = ''
  728.     is_hp = back_end in ('hp', 'hpfax', 'hpaio')
  729.     if not m.group(2).lower():
  730.         pass
  731.     bus = ''
  732.     if bus not in ('usb', 'net', 'bt', 'fw', 'par'):
  733.         log.debug('Device URI %s is invalid/unknown' % device_uri)
  734.         raise Error(ERROR_INVALID_DEVICE_URI)
  735.     bus not in ('usb', 'net', 'bt', 'fw', 'par')
  736.     if not m.group(3):
  737.         pass
  738.     model = ''
  739.     if not m.group(4):
  740.         pass
  741.     serial = ''
  742.     if not m.group(5):
  743.         pass
  744.     dev_file = ''
  745.     if not m.group(6):
  746.         pass
  747.     host = ''
  748.     zc = ''
  749.     if not host:
  750.         if not m.group(7):
  751.             pass
  752.         zc = host = ''
  753.     
  754.     if not m.group(8):
  755.         pass
  756.     port = 1
  757.     if bus == 'net':
  758.         
  759.         try:
  760.             port = int(port)
  761.         except (ValueError, TypeError):
  762.             port = 1
  763.  
  764.         if port == 0:
  765.             port = 1
  766.         
  767.     
  768.     log.debug('%s: back_end:%s is_hp:%s bus:%s model:%s serial:%s dev_file:%s host:%s zc:%s port:%s' % (device_uri, back_end, is_hp, bus, model, serial, dev_file, host, zc, port))
  769.     return (back_end, is_hp, bus, model, serial, dev_file, host, zc, port)
  770.  
  771.  
  772. def isLocal(bus):
  773.     return bus in ('par', 'usb', 'fw', 'bt')
  774.  
  775.  
  776. def isNetwork(bus):
  777.     return bus in ('net',)
  778.  
  779.  
  780. def __checkFilter(filter, mq):
  781.     for f, p in filter.items():
  782.         if f is not None:
  783.             (op, val) = p
  784.             if not op(mq[f], val):
  785.                 return False
  786.             continue
  787.         op(mq[f], val)
  788.     
  789.     return True
  790.  
  791.  
  792. def validateBusList(bus, allow_cups = True):
  793.     for b in bus:
  794.         if allow_cups:
  795.             vb = VALID_BUSES
  796.         else:
  797.             vb = VALID_BUSES_WO_CUPS
  798.         if b not in vb:
  799.             log.error('Invalid bus name: %s' % b)
  800.             return False
  801.     
  802.     return True
  803.  
  804.  
  805. def validateFilterList(filter):
  806.     if filter is None:
  807.         return True
  808.     for f in filter:
  809.         if f not in VALID_FILTERS:
  810.             log.error("Invalid term '%s' in filter list" % f)
  811.             return False
  812.     
  813.     return True
  814.  
  815. inter_pat = re.compile('%(.*)%', re.IGNORECASE)
  816. st = StringTable()
  817. strings_init = False
  818.  
  819. def initStrings():
  820.     global strings_init
  821.     strings_init = True
  822.     cycles = 0
  823.     while True:
  824.         found = False
  825.         for s in st.string_table:
  826.             (short_string, long_string) = st.string_table[s]
  827.             short_replace = short_string
  828.             long_replace = long_string
  829.             
  830.             try:
  831.                 short_match = inter_pat.match(short_string).group(1)
  832.             except (AttributeError, TypeError):
  833.                 short_match = None
  834.  
  835.             if short_match is not None:
  836.                 found = True
  837.                 
  838.                 try:
  839.                     (short_replace, dummy) = st.string_table[short_match]
  840.                 except KeyError:
  841.                     log.error('String interpolation error: %s' % short_match)
  842.                 except:
  843.                     None<EXCEPTION MATCH>KeyError
  844.                 
  845.  
  846.             None<EXCEPTION MATCH>KeyError
  847.             
  848.             try:
  849.                 long_match = inter_pat.match(long_string).group(1)
  850.             except (AttributeError, TypeError):
  851.                 long_match = None
  852.  
  853.             if long_match is not None:
  854.                 found = True
  855.                 
  856.                 try:
  857.                     (dummy, long_replace) = st.string_table[long_match]
  858.                 except KeyError:
  859.                     log.error('String interpolation error: %s' % long_match)
  860.                 except:
  861.                     None<EXCEPTION MATCH>KeyError
  862.                 
  863.  
  864.             None<EXCEPTION MATCH>KeyError
  865.             if found:
  866.                 st.string_table[s] = (short_replace, long_replace)
  867.                 continue
  868.         
  869.         if not found:
  870.             break
  871.             continue
  872.         cycles += 1
  873.         if cycles > 1000:
  874.             break
  875.             continue
  876.  
  877.  
  878. def queryString(string_id, typ = 0):
  879.     if not strings_init:
  880.         initStrings()
  881.     
  882.     s = st.string_table.get(str(string_id), ('', ''))[typ]
  883.     if type(s) == type(''):
  884.         return s
  885.     return s()
  886.  
  887. AGENT_types = {
  888.     AGENT_TYPE_NONE: 'invalid',
  889.     AGENT_TYPE_BLACK: 'black',
  890.     AGENT_TYPE_CMY: 'cmy',
  891.     AGENT_TYPE_KCM: 'kcm',
  892.     AGENT_TYPE_CYAN: 'cyan',
  893.     AGENT_TYPE_MAGENTA: 'magenta',
  894.     AGENT_TYPE_YELLOW: 'yellow',
  895.     AGENT_TYPE_CYAN_LOW: 'photo_cyan',
  896.     AGENT_TYPE_MAGENTA_LOW: 'photo_magenta',
  897.     AGENT_TYPE_YELLOW_LOW: 'photo_yellow',
  898.     AGENT_TYPE_GGK: 'photo_gray',
  899.     AGENT_TYPE_BLUE: 'photo_blue',
  900.     AGENT_TYPE_KCMY_CM: 'kcmy_cm',
  901.     AGENT_TYPE_LC_LM: 'photo_cyan_and_photo_magenta',
  902.     AGENT_TYPE_LG_PK: 'light_gray_and_photo_black',
  903.     AGENT_TYPE_LG: 'light_gray',
  904.     AGENT_TYPE_G: 'medium_gray',
  905.     AGENT_TYPE_PG: 'photo_gray',
  906.     AGENT_TYPE_C_M: 'cyan_and_magenta',
  907.     AGENT_TYPE_K_Y: 'black_and_yellow',
  908.     AGENT_TYPE_UNSPECIFIED: 'unspecified' }
  909. AGENT_kinds = {
  910.     AGENT_KIND_NONE: 'invalid',
  911.     AGENT_KIND_HEAD: 'head',
  912.     AGENT_KIND_SUPPLY: 'supply',
  913.     AGENT_KIND_HEAD_AND_SUPPLY: 'cartridge',
  914.     AGENT_KIND_TONER_CARTRIDGE: 'toner',
  915.     AGENT_KIND_MAINT_KIT: 'maint_kit',
  916.     AGENT_KIND_ADF_KIT: 'adf_kit',
  917.     AGENT_KIND_DRUM_KIT: 'drum_kit',
  918.     AGENT_KIND_TRANSFER_KIT: 'transfer_kit',
  919.     AGENT_KIND_INT_BATTERY: 'battery',
  920.     AGENT_KIND_UNKNOWN: 'unknown' }
  921. AGENT_healths = {
  922.     AGENT_HEALTH_OK: 'ok',
  923.     AGENT_HEALTH_MISINSTALLED: 'misinstalled',
  924.     AGENT_HEALTH_INCORRECT: 'incorrect',
  925.     AGENT_HEALTH_FAILED: 'failed',
  926.     AGENT_HEALTH_OVERTEMP: 'overtemp',
  927.     AGENT_HEALTH_CHARGING: 'charging',
  928.     AGENT_HEALTH_DISCHARGING: 'discharging' }
  929. AGENT_levels = {
  930.     AGENT_LEVEL_TRIGGER_MAY_BE_LOW: 'low',
  931.     AGENT_LEVEL_TRIGGER_PROBABLY_OUT: 'low',
  932.     AGENT_LEVEL_TRIGGER_ALMOST_DEFINITELY_OUT: 'out' }
  933. string_cache = { }
  934.  
  935. class Device(object):
  936.     
  937.     def __init__(self, device_uri, printer_name = None, service = None, callback = None, disable_dbus = False):
  938.         global dbus_disabled
  939.         log.debug('Device URI: %s' % device_uri)
  940.         log.debug('Printer: %s' % printer_name)
  941.         dbus_disabled = disable_dbus
  942.         if not disable_dbus:
  943.             if service is None:
  944.                 (self.dbus_avail, self.service, session_bus) = init_dbus()
  945.             else:
  946.                 self.dbus_avail = True
  947.                 self.service = service
  948.         else:
  949.             self.dbus_avail = False
  950.             self.service = None
  951.         self.last_event = None
  952.         printers = cups.getPrinters()
  953.         if device_uri is None and printer_name is not None:
  954.             for p in printers:
  955.                 if p.name.lower() == printer_name.lower():
  956.                     device_uri = p.device_uri
  957.                     log.debug('Device URI: %s' % device_uri)
  958.                     break
  959.                     continue
  960.             else:
  961.                 raise Error(ERROR_DEVICE_NOT_FOUND)
  962.         self.device_uri = device_uri
  963.         self.callback = callback
  964.         self.device_type = DEVICE_TYPE_UNKNOWN
  965.         if self.device_uri is None:
  966.             raise Error(ERROR_DEVICE_NOT_FOUND)
  967.         self.device_uri is None
  968.         if self.device_uri.startswith('hp:'):
  969.             self.device_type = DEVICE_TYPE_PRINTER
  970.         elif self.device_uri.startswith('hpaio:'):
  971.             self.device_type = DEVICE_TYPE_SCANNER
  972.         elif self.device_uri.startswith('hpfax:'):
  973.             self.device_type = DEVICE_TYPE_FAX
  974.         
  975.         
  976.         try:
  977.             (self.back_end, self.is_hp, self.bus, self.model, self.serial, self.dev_file, self.host, self.zc, self.port) = parseDeviceURI(self.device_uri)
  978.         except Error:
  979.             self.io_state = IO_STATE_NON_HP
  980.             raise Error(ERROR_INVALID_DEVICE_URI)
  981.  
  982.         log.debug('URI: backend=%s, is_hp=%s, bus=%s, model=%s, serial=%s, dev=%s, host=%s, port=%d' % (self.back_end, self.is_hp, self.bus, self.model, self.serial, self.dev_file, self.host, self.port))
  983.         self.model_ui = models.normalizeModelUIName(self.model)
  984.         self.model = models.normalizeModelName(self.model)
  985.         log.debug('Model/UI model: %s/%s' % (self.model, self.model_ui))
  986.         self.mq = { }
  987.         self.dq = { }
  988.         self.icon = 'default_printer'
  989.         self.cups_printers = []
  990.         self.channels = { }
  991.         self.device_id = -1
  992.         self.r_values = None
  993.         self.deviceID = ''
  994.         self.panel_check = True
  995.         self.io_state = IO_STATE_HP_READY
  996.         self.is_local = isLocal(self.bus)
  997.         self.hist = []
  998.         self.supported = False
  999.         self.queryModel()
  1000.         if not self.supported:
  1001.             log.error('Unsupported model: %s' % self.model)
  1002.             self.error_code = STATUS_DEVICE_UNSUPPORTED
  1003.             self.sendEvent(self.error_code)
  1004.         else:
  1005.             self.supported = True
  1006.         self.mq.update({
  1007.             'model': self.model,
  1008.             'model-ui': self.model_ui })
  1009.         self.error_state = ERROR_STATE_ERROR
  1010.         self.device_state = DEVICE_STATE_NOT_FOUND
  1011.         self.status_code = EVENT_ERROR_DEVICE_NOT_FOUND
  1012.         self.updateCUPSPrinters()
  1013.         if self.mq.get('fax-type', FAX_TYPE_NONE) != FAX_TYPE_NONE:
  1014.             self.dq.update({
  1015.                 'fax-uri': self.device_uri.replace('hp:/', 'hpfax:/').replace('hpaio:/', 'hpfax:/') })
  1016.         
  1017.         if self.mq.get('scan-type', SCAN_TYPE_NONE) != SCAN_TYPE_NONE:
  1018.             self.dq.update({
  1019.                 'scan-uri': self.device_uri.replace('hp:/', 'hpaio:/').replace('hpfax:/', 'hpaio:/') })
  1020.         
  1021.         self.dq.update({
  1022.             'back-end': self.back_end,
  1023.             'is-hp': self.is_hp,
  1024.             'serial': self.serial,
  1025.             'dev-file': self.dev_file,
  1026.             'host': self.host,
  1027.             'port': self.port,
  1028.             'cups-printers': ','.join(self.cups_printers),
  1029.             'status-code': self.status_code,
  1030.             'status-desc': '',
  1031.             'deviceid': '',
  1032.             'panel': 0,
  1033.             'panel-line1': '',
  1034.             'panel-line2': '',
  1035.             'device-state': self.device_state,
  1036.             'error-state': self.error_state,
  1037.             'device-uri': self.device_uri,
  1038.             'cups-uri': self.device_uri.replace('hpfax:/', 'hp:/').replace('hpaio:/', 'hp:/') })
  1039.         self.device_vars = {
  1040.             'URI': self.device_uri,
  1041.             'DEVICE_URI': self.device_uri,
  1042.             'SCAN_URI': self.device_uri.replace('hp:', 'hpaio:'),
  1043.             'SANE_URI': self.device_uri.replace('hp:', 'hpaio:'),
  1044.             'FAX_URI': self.device_uri.replace('hp:', 'hpfax:'),
  1045.             'PRINTER': self.first_cups_printer,
  1046.             'HOME': prop.home_dir }
  1047.  
  1048.     
  1049.     def sendEvent(self, event_code, printer_name = '', job_id = 0, title = ''):
  1050.         if self.dbus_avail and self.service is not None:
  1051.             
  1052.             try:
  1053.                 log.debug('Sending event %d to hpssd...' % event_code)
  1054.                 self.service.SendEvent(self.device_uri, printer_name, event_code, prop.username, job_id, title)
  1055.             except dbus.exceptions.DBusException:
  1056.                 e = None
  1057.                 log.debug('dbus call to SendEvent() failed.')
  1058.             except:
  1059.                 None<EXCEPTION MATCH>dbus.exceptions.DBusException
  1060.             
  1061.  
  1062.         None<EXCEPTION MATCH>dbus.exceptions.DBusException
  1063.  
  1064.     
  1065.     def quit(self):
  1066.         pass
  1067.  
  1068.     
  1069.     def queryModel(self):
  1070.         if not self.mq:
  1071.             self.mq = queryModelByURI(self.device_uri)
  1072.         
  1073.         self.supported = bool(self.mq)
  1074.         if self.supported:
  1075.             for m in self.mq:
  1076.                 self.__dict__[m.replace('-', '_')] = self.mq[m]
  1077.             
  1078.         
  1079.  
  1080.     
  1081.     def queryString(self, string_id):
  1082.         return queryString(string_id)
  1083.  
  1084.     
  1085.     def open(self, open_for_printing = False):
  1086.         if self.supported and self.io_state in (IO_STATE_HP_READY, IO_STATE_HP_NOT_AVAIL):
  1087.             prev_device_state = self.device_state
  1088.             self.io_state = IO_STATE_HP_NOT_AVAIL
  1089.             self.device_state = DEVICE_STATE_NOT_FOUND
  1090.             self.error_state = ERROR_STATE_ERROR
  1091.             self.status_code = EVENT_ERROR_DEVICE_NOT_FOUND
  1092.             self.device_id = -1
  1093.             self.open_for_printing = open_for_printing
  1094.             if open_for_printing:
  1095.                 log.debug('Opening device: %s (for printing)' % self.device_uri)
  1096.                 self.io_mode = self.mq.get('io-mode', hpmudext.HPMUD_UNI_MODE)
  1097.             else:
  1098.                 log.debug('Opening device: %s (not for printing)' % self.device_uri)
  1099.                 self.io_mode = self.mq.get('io-mfp-mode', hpmudext.HPMUD_UNI_MODE)
  1100.             log.debug('I/O mode=%d' % self.io_mode)
  1101.             (result_code, self.device_id) = hpmudext.open_device(self.device_uri, self.io_mode)
  1102.             if result_code != hpmudext.HPMUD_R_OK:
  1103.                 self.error_state = ERROR_STATE_ERROR
  1104.                 self.error_code = result_code + ERROR_CODE_BASE
  1105.                 self.sendEvent(self.error_code)
  1106.                 if result_code == hpmudext.HPMUD_R_DEVICE_BUSY:
  1107.                     log.error('Device busy: %s' % self.device_uri)
  1108.                 else:
  1109.                     log.error('Unable to communicate with device (code=%d): %s' % (result_code, self.device_uri))
  1110.                 self.last_event = Event(self.device_uri, '', EVENT_ERROR_DEVICE_NOT_FOUND, prop.username, 0, '', time.time())
  1111.                 raise Error(ERROR_DEVICE_NOT_FOUND)
  1112.             result_code != hpmudext.HPMUD_R_OK
  1113.             log.debug('device-id=%d' % self.device_id)
  1114.             self.io_state = IO_STATE_HP_OPEN
  1115.             self.error_state = ERROR_STATE_CLEAR
  1116.             log.debug('Opened device: %s (backend=%s, is_hp=%s, bus=%s, model=%s, dev=%s, serial=%s, host=%s, port=%d)' % (self.back_end, self.device_uri, self.is_hp, self.bus, self.model, self.dev_file, self.serial, self.host, self.port))
  1117.             if prev_device_state == DEVICE_STATE_NOT_FOUND:
  1118.                 self.device_state = DEVICE_STATE_JUST_FOUND
  1119.             else:
  1120.                 self.device_state = DEVICE_STATE_FOUND
  1121.             self.getDeviceID()
  1122.             self.getSerialNumber()
  1123.             return self.device_id
  1124.         self.io_state in (IO_STATE_HP_READY, IO_STATE_HP_NOT_AVAIL)
  1125.  
  1126.     
  1127.     def close(self):
  1128.         if self.io_state == IO_STATE_HP_OPEN:
  1129.             log.debug('Closing device...')
  1130.             if len(self.channels) > 0:
  1131.                 for c in self.channels.keys():
  1132.                     self._Device__closeChannel(c)
  1133.                 
  1134.             
  1135.             result_code = hpmudext.close_device(self.device_id)
  1136.             log.debug('Result-code = %d' % result_code)
  1137.             self.channels.clear()
  1138.             self.io_state = IO_STATE_HP_READY
  1139.         
  1140.  
  1141.     
  1142.     def __openChannel(self, service_name):
  1143.         
  1144.         try:
  1145.             if self.io_state == IO_STATE_HP_OPEN:
  1146.                 if service_name == hpmudext.HPMUD_S_PRINT_CHANNEL and not (self.open_for_printing):
  1147.                     self.close()
  1148.                     self.open(True)
  1149.                 elif service_name != hpmudext.HPMUD_S_PRINT_CHANNEL and self.open_for_printing:
  1150.                     self.close()
  1151.                     self.open(False)
  1152.                 
  1153.             else:
  1154.                 self.open(service_name == hpmudext.HPMUD_S_PRINT_CHANNEL)
  1155.         except:
  1156.             log.error('unable to open channel')
  1157.             return -1
  1158.  
  1159.         service_name = service_name.upper()
  1160.         if service_name not in self.channels:
  1161.             log.debug('Opening %s channel...' % service_name)
  1162.             (result_code, channel_id) = hpmudext.open_channel(self.device_id, service_name)
  1163.             self.channels[service_name] = channel_id
  1164.             log.debug('channel-id=%d' % channel_id)
  1165.             return channel_id
  1166.         return self.channels[service_name]
  1167.  
  1168.     
  1169.     def openChannel(self, service_name):
  1170.         return self._Device__openChannel(service_name)
  1171.  
  1172.     
  1173.     def openPrint(self):
  1174.         return self._Device__openChannel(hpmudext.HPMUD_S_PRINT_CHANNEL)
  1175.  
  1176.     
  1177.     def openFax(self):
  1178.         return self._Device__openChannel(hpmudext.HPMUD_S_FAX_SEND_CHANNEL)
  1179.  
  1180.     
  1181.     def openPCard(self):
  1182.         return self._Device__openChannel(hpmudext.HPMUD_S_MEMORY_CARD_CHANNEL)
  1183.  
  1184.     
  1185.     def openEWS(self):
  1186.         return self._Device__openChannel(hpmudext.HPMUD_S_EWS_CHANNEL)
  1187.  
  1188.     
  1189.     def closePrint(self):
  1190.         return self._Device__closeChannel(hpmudext.HPMUD_S_PRINT_CHANNEL)
  1191.  
  1192.     
  1193.     def closePCard(self):
  1194.         return self._Device__closeChannel(hpmudext.HPMUD_S_MEMORY_CARD_CHANNEL)
  1195.  
  1196.     
  1197.     def closeFax(self):
  1198.         return self._Device__closeChannel(hpmudext.HPMUD_S_FAX_SEND_CHANNEL)
  1199.  
  1200.     
  1201.     def openPML(self):
  1202.         return self._Device__openChannel(hpmudext.HPMUD_S_PML_CHANNEL)
  1203.  
  1204.     
  1205.     def openWifiConfig(self):
  1206.         return self._Device__openChannel(hpmudext.HPMUD_S_WIFI_CHANNEL)
  1207.  
  1208.     
  1209.     def closePML(self):
  1210.         return self._Device__closeChannel(hpmudext.HPMUD_S_PML_CHANNEL)
  1211.  
  1212.     
  1213.     def closeEWS(self):
  1214.         return self._Device__closeChannel(hpmudext.HPMUD_S_EWS_CHANNEL)
  1215.  
  1216.     
  1217.     def openCfgUpload(self):
  1218.         return self._Device__openChannel(hpmudext.HPMUD_S_CONFIG_UPLOAD_CHANNEL)
  1219.  
  1220.     
  1221.     def closeCfgUpload(self):
  1222.         return self._Device__closeChannel(hpmudext.HPMUD_S_CONFIG_UPLOAD_CHANNEL)
  1223.  
  1224.     
  1225.     def openCfgDownload(self):
  1226.         return self._Device__openChannel(hpmudext.HPMUD_S_CONFIG_DOWNLOAD_CHANNEL)
  1227.  
  1228.     
  1229.     def closeCfgDownload(self):
  1230.         return self._Device__closeChannel(hpmudext.HPMUD_S_CONFIG_DOWNLOAD_CHANNEL)
  1231.  
  1232.     
  1233.     def openSoapFax(self):
  1234.         return self._Device__openChannel(hpmudext.HPMUD_S_SOAP_FAX)
  1235.  
  1236.     
  1237.     def closeSoapFax(self):
  1238.         return self._Device__closeChannel(hpmudext.HPMUD_S_SOAP_FAX)
  1239.  
  1240.     
  1241.     def closeWifiConfig(self):
  1242.         return self._Device__closeChannel(hpmudext.HPMUD_S_WIFI_CHANNEL)
  1243.  
  1244.     
  1245.     def __closeChannel(self, service_name):
  1246.         if self.io_state == IO_STATE_HP_OPEN:
  1247.             service_name = service_name.upper()
  1248.             if service_name in self.channels:
  1249.                 log.debug('Closing %s channel...' % service_name)
  1250.                 result_code = hpmudext.close_channel(self.device_id, self.channels[service_name])
  1251.                 del self.channels[service_name]
  1252.             
  1253.         
  1254.  
  1255.     
  1256.     def closeChannel(self, service_name):
  1257.         return self._Device__closeChannel(service_name)
  1258.  
  1259.     
  1260.     def getDeviceID(self):
  1261.         needs_close = False
  1262.         if self.io_state != IO_STATE_HP_OPEN:
  1263.             
  1264.             try:
  1265.                 self.open()
  1266.             except:
  1267.                 return -1
  1268.  
  1269.             needs_close = True
  1270.         
  1271.         (result_code, data) = hpmudext.get_device_id(self.device_id)
  1272.         if result_code != hpmudext.HPMUD_R_OK:
  1273.             self.raw_deviceID = ''
  1274.             self.deviceID = { }
  1275.         else:
  1276.             self.raw_deviceID = data
  1277.             self.deviceID = parseDeviceID(data)
  1278.         if needs_close:
  1279.             self.close()
  1280.         
  1281.         return self.deviceID
  1282.  
  1283.     
  1284.     def getSerialNumber(self):
  1285.         if self.serial:
  1286.             return None
  1287.         
  1288.         try:
  1289.             self.serial = self.deviceID['SN']
  1290.         except KeyError:
  1291.             self.serial
  1292.             self.serial
  1293.         except:
  1294.             self.serial
  1295.  
  1296.         if self.serial:
  1297.             return None
  1298.         if self.serial is None:
  1299.             self.serial = ''
  1300.         
  1301.  
  1302.     
  1303.     def getThreeBitStatus(self):
  1304.         pass
  1305.  
  1306.     
  1307.     def getStatusFromDeviceID(self):
  1308.         self.getDeviceID()
  1309.         return status.parseStatus(parseDeviceID(self.raw_deviceID))
  1310.  
  1311.     
  1312.     def __parseRValues(self, r_value):
  1313.         r_value_str = str(r_value)
  1314.         r_value_str = ''.join([
  1315.             '0' * (9 - len(r_value_str)),
  1316.             r_value_str])
  1317.         rg = r_value_str[:3]
  1318.         rr = r_value_str[3:]
  1319.         r_value = int(rr)
  1320.         self.r_values = (r_value, r_value_str, rg, rr)
  1321.         return (r_value, r_value_str, rg, rr)
  1322.  
  1323.     
  1324.     def getRValues(self, r_type, status_type, dynamic_counters):
  1325.         (r_value, r_value_str, rg, rr) = (0, '000000000', '000', '000000')
  1326.         if r_type > 0 and dynamic_counters != STATUS_DYNAMIC_COUNTERS_NONE:
  1327.             if self.r_values is None:
  1328.                 if self.dbus_avail:
  1329.                     
  1330.                     try:
  1331.                         r_value = int(self.service.GetCachedIntValue(self.device_uri, 'r_value'))
  1332.                     except dbus.exceptions.DBusException:
  1333.                         e = None
  1334.                         log.debug('dbus call to GetCachedIntValue() failed.')
  1335.                         r_value = -1
  1336.                     except:
  1337.                         None<EXCEPTION MATCH>dbus.exceptions.DBusException
  1338.                     
  1339.  
  1340.                 None<EXCEPTION MATCH>dbus.exceptions.DBusException
  1341.                 if r_value != -1:
  1342.                     log.debug('r_value=%d' % r_value)
  1343.                     (r_value, r_value_str, rg, rr) = self._Device__parseRValues(r_value)
  1344.                     return (r_value, r_value_str, rg, rr)
  1345.             
  1346.             if self.r_values is None:
  1347.                 if status_type == STATUS_TYPE_S and self.is_local and dynamic_counters != STATUS_DYNAMIC_COUNTERS_PML_SNMP:
  1348.                     
  1349.                     try:
  1350.                         r_value = self.getDynamicCounter(140)
  1351.                         if r_value is not None:
  1352.                             log.debug('r_value=%d' % r_value)
  1353.                             (r_value, r_value_str, rg, rr) = self._Device__parseRValues(r_value)
  1354.                             if self.dbus_avail:
  1355.                                 
  1356.                                 try:
  1357.                                     self.service.SetCachedIntValue(self.device_uri, 'r_value', r_value)
  1358.                                 except dbus.exceptions.DBusException:
  1359.                                     e = None
  1360.                                     log.debug('dbus call to SetCachedIntValue() failed.')
  1361.                                 except:
  1362.                                     None<EXCEPTION MATCH>dbus.exceptions.DBusException
  1363.                                 
  1364.  
  1365.                             None<EXCEPTION MATCH>dbus.exceptions.DBusException
  1366.                         else:
  1367.                             log.error('Error attempting to read r-value (2).')
  1368.                             r_value = 0
  1369.                     except Error:
  1370.                         log.error('Error attempting to read r-value (1).')
  1371.                         r_value = 0
  1372.                     finally:
  1373.                         self.closePrint()
  1374.  
  1375.                 elif status_type == STATUS_TYPE_S and dynamic_counters == STATUS_DYNAMIC_COUNTERS_PCL or not (self.is_local) or dynamic_counters == STATUS_DYNAMIC_COUNTERS_PML_SNMP:
  1376.                     
  1377.                     try:
  1378.                         (result_code, r_value) = self.getPML(pml.OID_R_SETTING)
  1379.                         if r_value is not None:
  1380.                             log.debug('r_value=%d' % r_value)
  1381.                             (r_value, r_value_str, rg, rr) = self._Device__parseRValues(r_value)
  1382.                             if self.dbus_avail:
  1383.                                 
  1384.                                 try:
  1385.                                     self.service.SetCachedIntValue(self.device_uri, 'r_value', r_value)
  1386.                                 except dbus.exceptions.DBusException:
  1387.                                     e = None
  1388.                                     log.debug('dbus call to SetCachedIntValue() failed.')
  1389.                                 except:
  1390.                                     None<EXCEPTION MATCH>dbus.exceptions.DBusException
  1391.                                 
  1392.  
  1393.                             None<EXCEPTION MATCH>dbus.exceptions.DBusException
  1394.                         else:
  1395.                             r_value = 0
  1396.                     finally:
  1397.                         self.closePML()
  1398.  
  1399.                 
  1400.             else:
  1401.                 (r_value, r_value_str, rg, rr) = self.r_values
  1402.         
  1403.         return (r_value, r_value_str, rg, rr)
  1404.  
  1405.     
  1406.     def __queryFax(self, quick = False, reread_cups_printers = False):
  1407.         io_mode = self.mq.get('io-mode', IO_MODE_UNI)
  1408.         self.status_code = STATUS_PRINTER_IDLE
  1409.         if io_mode != IO_MODE_UNI:
  1410.             if self.device_state != DEVICE_STATE_NOT_FOUND:
  1411.                 if self.tech_type in (TECH_TYPE_MONO_INK, TECH_TYPE_COLOR_INK):
  1412.                     
  1413.                     try:
  1414.                         self.getDeviceID()
  1415.                     except Error:
  1416.                         e = None
  1417.                         log.error('Error getting device ID.')
  1418.                         self.last_event = Event(self.device_uri, '', ERROR_DEVICE_IO_ERROR, prop.username, 0, '', time.time())
  1419.                         raise Error(ERROR_DEVICE_IO_ERROR)
  1420.                     except:
  1421.                         None<EXCEPTION MATCH>Error
  1422.                     
  1423.  
  1424.                 None<EXCEPTION MATCH>Error
  1425.                 status_desc = self.queryString(self.status_code)
  1426.                 self.dq.update({
  1427.                     'serial': self.serial,
  1428.                     'cups-printers': ','.join(self.cups_printers),
  1429.                     'status-code': self.status_code,
  1430.                     'status-desc': status_desc,
  1431.                     'deviceid': self.raw_deviceID,
  1432.                     'panel': 0,
  1433.                     'panel-line1': '',
  1434.                     'panel-line2': '',
  1435.                     'device-state': self.device_state,
  1436.                     'error-state': self.error_state })
  1437.             
  1438.             log.debug('Fax activity check...')
  1439.             (tx_active, rx_active) = status.getFaxStatus(self)
  1440.             if tx_active:
  1441.                 self.status_code = STATUS_FAX_TX_ACTIVE
  1442.             elif rx_active:
  1443.                 self.status_code = STATUS_FAX_RX_ACTIVE
  1444.             
  1445.             self.error_state = STATUS_TO_ERROR_STATE_MAP.get(self.status_code, ERROR_STATE_CLEAR)
  1446.             self.error_code = self.status_code
  1447.             self.sendEvent(self.error_code)
  1448.             
  1449.             try:
  1450.                 self.dq.update({
  1451.                     'status-desc': self.queryString(self.status_code),
  1452.                     'error-state': self.error_state })
  1453.             except (KeyError, Error):
  1454.                 self.dq.update({
  1455.                     'status-desc': '',
  1456.                     'error-state': ERROR_STATE_CLEAR })
  1457.  
  1458.             if self.panel_check:
  1459.                 self.panel_check = bool(self.mq.get('panel-check-type', 0))
  1460.             
  1461.             status_type = self.mq.get('status-type', STATUS_TYPE_NONE)
  1462.             if self.panel_check and status_type in (STATUS_TYPE_LJ, STATUS_TYPE_S, STATUS_TYPE_VSTATUS) and io_mode != IO_MODE_UNI:
  1463.                 log.debug('Panel check...')
  1464.                 
  1465.                 try:
  1466.                     (self.panel_check, line1, line2) = status.PanelCheck(self)
  1467.                 finally:
  1468.                     self.closePML()
  1469.  
  1470.                 self.dq.update({
  1471.                     'panel': int(self.panel_check),
  1472.                     'panel-line1': line1,
  1473.                     'panel-line2': line2 })
  1474.             
  1475.             if not quick and reread_cups_printers:
  1476.                 self.updateCUPSPrinters()
  1477.             
  1478.         
  1479.         for d in self.dq:
  1480.             self.__dict__[d.replace('-', '_')] = self.dq[d]
  1481.         
  1482.         self.last_event = Event(self.device_uri, '', self.status_code, prop.username, 0, '', time.time())
  1483.         log.debug(self.dq)
  1484.  
  1485.     
  1486.     def updateCUPSPrinters(self):
  1487.         self.cups_printers = []
  1488.         log.debug('Re-reading CUPS printer queue information.')
  1489.         printers = cups.getPrinters()
  1490.         for p in printers:
  1491.             if self.device_uri == p.device_uri:
  1492.                 self.cups_printers.append(p.name)
  1493.                 self.state = p.state
  1494.                 if self.io_state == IO_STATE_NON_HP:
  1495.                     self.model = p.makemodel.split(',')[0]
  1496.                 
  1497.             self.io_state == IO_STATE_NON_HP
  1498.         
  1499.         self.dq.update({
  1500.             'cups-printers': ','.join(self.cups_printers) })
  1501.         
  1502.         try:
  1503.             self.first_cups_printer = self.cups_printers[0]
  1504.         except IndexError:
  1505.             self.first_cups_printer = ''
  1506.  
  1507.  
  1508.     
  1509.     def queryDevice(self, quick = False, reread_cups_printers = False):
  1510.         if not self.supported:
  1511.             self.dq = { }
  1512.             self.last_event = Event(self.device_uri, '', STATUS_DEVICE_UNSUPPORTED, prop.username, 0, '', time.time())
  1513.             return None
  1514.         if self.device_type == DEVICE_TYPE_FAX:
  1515.             return self._Device__queryFax(quick, reread_cups_printers)
  1516.         r_type = self.mq.get('r-type', 0)
  1517.         tech_type = self.mq.get('tech-type', TECH_TYPE_NONE)
  1518.         status_type = self.mq.get('status-type', STATUS_TYPE_NONE)
  1519.         battery_check = self.mq.get('status-battery-check', STATUS_BATTERY_CHECK_NONE)
  1520.         dynamic_counters = self.mq.get('status-dynamic-counters', STATUS_DYNAMIC_COUNTERS_NONE)
  1521.         io_mode = self.mq.get('io-mode', IO_MODE_UNI)
  1522.         io_mfp_mode = self.mq.get('io-mfp-mode', IO_MODE_UNI)
  1523.         status_code = STATUS_UNKNOWN
  1524.         agents = []
  1525.         if self.device_state != DEVICE_STATE_NOT_FOUND:
  1526.             if self.tech_type in (TECH_TYPE_MONO_INK, TECH_TYPE_COLOR_INK):
  1527.                 
  1528.                 try:
  1529.                     self.getDeviceID()
  1530.                 except Error:
  1531.                     self.device_type == DEVICE_TYPE_FAX
  1532.                     e = self.device_type == DEVICE_TYPE_FAX
  1533.                     self.supported
  1534.                     log.error('Error getting device ID.')
  1535.                     self.last_event = Event(self.device_uri, '', ERROR_DEVICE_IO_ERROR, prop.username, 0, '', time.time())
  1536.                     raise Error(ERROR_DEVICE_IO_ERROR)
  1537.                 except:
  1538.                     self.device_type == DEVICE_TYPE_FAX<EXCEPTION MATCH>Error
  1539.                 
  1540.  
  1541.             self.device_type == DEVICE_TYPE_FAX
  1542.             status_desc = self.queryString(self.status_code)
  1543.             self.dq.update({
  1544.                 'serial': self.serial,
  1545.                 'cups-printers': ','.join(self.cups_printers),
  1546.                 'status-code': self.status_code,
  1547.                 'status-desc': status_desc,
  1548.                 'deviceid': self.raw_deviceID,
  1549.                 'panel': 0,
  1550.                 'panel-line1': '',
  1551.                 'panel-line2': '',
  1552.                 'device-state': self.device_state,
  1553.                 'error-state': self.error_state })
  1554.             status_block = { }
  1555.             if status_type == STATUS_TYPE_NONE:
  1556.                 log.warn('No status available for device.')
  1557.                 status_block = {
  1558.                     'status-code': STATUS_UNKNOWN }
  1559.             elif status_type in (STATUS_TYPE_VSTATUS, STATUS_TYPE_S):
  1560.                 log.debug('Type 1/2 (S: or VSTATUS:) status')
  1561.                 status_block = status.parseStatus(self.deviceID)
  1562.             elif status_type in (STATUS_TYPE_LJ, STATUS_TYPE_PML_AND_PJL):
  1563.                 log.debug('Type 3/9 LaserJet PML(+PJL) status')
  1564.                 status_block = status.StatusType3(self, self.deviceID)
  1565.             elif status_type == STATUS_TYPE_LJ_XML:
  1566.                 log.debug('Type 6: LJ XML')
  1567.                 status_block = status.StatusType6(self)
  1568.             elif status_type == STATUS_TYPE_PJL:
  1569.                 log.debug('Type 8: LJ PJL')
  1570.                 status_block = status.StatusType8(self)
  1571.             else:
  1572.                 log.error('Unimplemented status type: %d' % status_type)
  1573.             if battery_check and io_mode != IO_MODE_UNI:
  1574.                 log.debug('Battery check...')
  1575.                 status.BatteryCheck(self, status_block, battery_check)
  1576.             
  1577.             if status_block:
  1578.                 log.debug(status_block)
  1579.                 self.dq.update(status_block)
  1580.                 
  1581.                 try:
  1582.                     status_block['agents']
  1583.                 except KeyError:
  1584.                     pass
  1585.  
  1586.                 agents = status_block['agents']
  1587.                 del self.dq['agents']
  1588.             
  1589.             status_code = self.dq.get('status-code', STATUS_UNKNOWN)
  1590.             self.error_state = STATUS_TO_ERROR_STATE_MAP.get(status_code, ERROR_STATE_CLEAR)
  1591.             self.error_code = status_code
  1592.             self.sendEvent(self.error_code)
  1593.             
  1594.             try:
  1595.                 self.dq.update({
  1596.                     'status-desc': self.queryString(status_code),
  1597.                     'error-state': self.error_state })
  1598.             except (KeyError, Error):
  1599.                 self.dq.update({
  1600.                     'status-desc': '',
  1601.                     'error-state': ERROR_STATE_CLEAR })
  1602.  
  1603.             r_value = 0
  1604.             if not quick and status_type != STATUS_TYPE_NONE:
  1605.                 if self.panel_check:
  1606.                     self.panel_check = bool(self.mq.get('panel-check-type', 0))
  1607.                 
  1608.                 if self.panel_check and status_type in (STATUS_TYPE_LJ, STATUS_TYPE_S, STATUS_TYPE_VSTATUS) and io_mode != IO_MODE_UNI:
  1609.                     log.debug('Panel check...')
  1610.                     
  1611.                     try:
  1612.                         (self.panel_check, line1, line2) = status.PanelCheck(self)
  1613.                     finally:
  1614.                         self.closePML()
  1615.  
  1616.                     self.dq.update({
  1617.                         'panel': int(self.panel_check),
  1618.                         'panel-line1': line1,
  1619.                         'panel-line2': line2 })
  1620.                 
  1621.                 if dynamic_counters != STATUS_DYNAMIC_COUNTERS_NONE and io_mode != IO_MODE_UNI:
  1622.                     (r_value, r_value_str, rg, rr) = self.getRValues(r_type, status_type, dynamic_counters)
  1623.                 else:
  1624.                     (r_value, r_value_str, rg, rr) = (0, '000000000', '000', '000000')
  1625.                 self.dq.update({
  1626.                     'r': r_value,
  1627.                     'rs': r_value_str,
  1628.                     'rg': rg,
  1629.                     'rr': rr })
  1630.             
  1631.             if not quick and reread_cups_printers:
  1632.                 self.updateCUPSPrinters()
  1633.             
  1634.             if not quick:
  1635.                 if r_value > 0 and self.mq.get('r%d-agent1-kind' % r_value, 0) == 0:
  1636.                     r_value = 0
  1637.                     self.dq.update({
  1638.                         'r': r_value,
  1639.                         'rs': r_value_str,
  1640.                         'rg': rg,
  1641.                         'rr': rr })
  1642.                 
  1643.                 (a, aa) = (1, 1)
  1644.                 while True:
  1645.                     mq_agent_kind = self.mq.get('r%d-agent%d-kind' % (r_value, a), -1)
  1646.                     if mq_agent_kind == -1:
  1647.                         break
  1648.                     
  1649.                     mq_agent_type = self.mq.get('r%d-agent%d-type' % (r_value, a), 0)
  1650.                     mq_agent_sku = self.mq.get('r%d-agent%d-sku' % (r_value, a), '')
  1651.                     found = False
  1652.                     log.debug('Looking for kind=%d, type=%d...' % (mq_agent_kind, mq_agent_type))
  1653.                     for agent in agents:
  1654.                         agent_kind = agent['kind']
  1655.                         agent_type = agent['type']
  1656.                         if agent_kind == mq_agent_kind and agent_type == mq_agent_type:
  1657.                             found = True
  1658.                             break
  1659.                             continue
  1660.                     
  1661.                     if found:
  1662.                         log.debug('found: r%d-kind%d-type%d' % (r_value, agent_kind, agent_type))
  1663.                         agent_health = agent.get('health', AGENT_HEALTH_OK)
  1664.                         agent_level = agent.get('level', 100)
  1665.                         agent_level_trigger = agent.get('level-trigger', AGENT_LEVEL_TRIGGER_SUFFICIENT_0)
  1666.                         log.debug('health=%d, level=%d, level_trigger=%d, status_code=%d' % (agent_health, agent_level, agent_level_trigger, status_code))
  1667.                         query = 'agent_%s_%s' % (AGENT_types.get(agent_type, 'unknown'), AGENT_kinds.get(agent_kind, 'unknown'))
  1668.                         agent_desc = self.queryString(query)
  1669.                         query = 'agent_health_ok'
  1670.                         if status_code == STATUS_PRINTER_IDLE or status_code == STATUS_PRINTER_OUT_OF_INK:
  1671.                             if (agent_health == AGENT_HEALTH_OK or agent_health == AGENT_HEALTH_FAIR_MODERATE or agent_kind == AGENT_KIND_HEAD) and agent_level_trigger >= AGENT_LEVEL_TRIGGER_MAY_BE_LOW:
  1672.                                 query = 'agent_level_%s' % AGENT_levels.get(agent_level_trigger, 'unknown')
  1673.                                 if tech_type in (TECH_TYPE_MONO_INK, TECH_TYPE_COLOR_INK):
  1674.                                     code = agent_type + STATUS_PRINTER_LOW_INK_BASE
  1675.                                 else:
  1676.                                     code = agent_type + STATUS_PRINTER_LOW_TONER_BASE
  1677.                                 self.dq['status-code'] = code
  1678.                                 self.dq['status-desc'] = self.queryString(code)
  1679.                                 self.dq['error-state'] = STATUS_TO_ERROR_STATE_MAP.get(code, ERROR_STATE_LOW_SUPPLIES)
  1680.                                 self.error_code = code
  1681.                                 self.sendEvent(self.error_code)
  1682.                                 if agent_level_trigger in (AGENT_LEVEL_TRIGGER_PROBABLY_OUT, AGENT_LEVEL_TRIGGER_ALMOST_DEFINITELY_OUT):
  1683.                                     query = 'agent_level_out'
  1684.                                 else:
  1685.                                     query = 'agent_level_low'
  1686.                                 agent_health_desc = self.queryString(query)
  1687.                                 self.dq.update({
  1688.                                     'agent%d-kind' % aa: agent_kind,
  1689.                                     'agent%d-type' % aa: agent_type,
  1690.                                     'agent%d-known' % aa: agent.get('known', False),
  1691.                                     'agent%d-sku' % aa: mq_agent_sku,
  1692.                                     'agent%d-level' % aa: agent_level,
  1693.                                     'agent%d-level-trigger' % aa: agent_level_trigger,
  1694.                                     'agent%d-ack' % aa: agent.get('ack', False),
  1695.                                     'agent%d-hp-ink' % aa: agent.get('hp-ink', False),
  1696.                                     'agent%d-health' % aa: agent_health,
  1697.                                     'agent%d-dvc' % aa: agent.get('dvc', 0),
  1698.                                     'agent%d-virgin' % aa: agent.get('virgin', False),
  1699.                                     'agent%d-desc' % aa: agent_desc,
  1700.                                     'agent%d-id' % aa: agent.get('id', 0),
  1701.                                     'agent%d-health-desc' % aa: agent_health_desc })
  1702.                             else:
  1703.                                 query = 'agent_health_%s' % AGENT_healths.get(agent_health, AGENT_HEALTH_OK)
  1704.                                 agent_health_desc = self.queryString(query)
  1705.                                 self.dq.update({
  1706.                                     'agent%d-kind' % aa: agent_kind,
  1707.                                     'agent%d-type' % aa: agent_type,
  1708.                                     'agent%d-known' % aa: False,
  1709.                                     'agent%d-sku' % aa: mq_agent_sku,
  1710.                                     'agent%d-level' % aa: agent_level,
  1711.                                     'agent%d-level-trigger' % aa: agent_level_trigger,
  1712.                                     'agent%d-ack' % aa: False,
  1713.                                     'agent%d-hp-ink' % aa: False,
  1714.                                     'agent%d-health' % aa: agent_health,
  1715.                                     'agent%d-dvc' % aa: 0,
  1716.                                     'agent%d-virgin' % aa: False,
  1717.                                     'agent%d-desc' % aa: agent_desc,
  1718.                                     'agent%d-id' % aa: 0,
  1719.                                     'agent%d-health-desc' % aa: agent_health_desc })
  1720.                         aa += 1
  1721.                     else:
  1722.                         log.debug('Not found: %d' % a)
  1723.                     a += 1
  1724.             
  1725.         else:
  1726.             r_value = 0
  1727.             if r_type > 0 and self.r_values is not None:
  1728.                 r_value = self.r_values[0]
  1729.             
  1730.             if r_value > 0 and self.mq.get('r%d-agent1-kind', 0) == 0:
  1731.                 r_value = 0
  1732.             
  1733.             a = 1
  1734.             while True:
  1735.                 mq_agent_kind = self.mq.get('r%d-agent%d-kind' % (r_value, a), 0)
  1736.                 if mq_agent_kind == 0:
  1737.                     break
  1738.                 
  1739.                 mq_agent_type = self.mq.get('r%d-agent%d-type' % (r_value, a), 0)
  1740.                 mq_agent_sku = self.mq.get('r%d-agent%d-sku' % (r_value, a), '')
  1741.                 query = 'agent_%s_%s' % (AGENT_types.get(mq_agent_type, 'unknown'), AGENT_kinds.get(mq_agent_kind, 'unknown'))
  1742.                 agent_desc = self.queryString(query)
  1743.                 self.dq.update({
  1744.                     'agent%d-kind' % a: mq_agent_kind,
  1745.                     'agent%d-type' % a: mq_agent_type,
  1746.                     'agent%d-known' % a: False,
  1747.                     'agent%d-sku' % a: mq_agent_sku,
  1748.                     'agent%d-level' % a: 0,
  1749.                     'agent%d-level-trigger' % a: AGENT_LEVEL_TRIGGER_ALMOST_DEFINITELY_OUT,
  1750.                     'agent%d-ack' % a: False,
  1751.                     'agent%d-hp-ink' % a: False,
  1752.                     'agent%d-health' % a: AGENT_HEALTH_MISINSTALLED,
  1753.                     'agent%d-dvc' % a: 0,
  1754.                     'agent%d-virgin' % a: False,
  1755.                     'agent%d-health-desc' % a: self.queryString('agent_health_unknown'),
  1756.                     'agent%d-desc' % a: agent_desc,
  1757.                     'agent%d-id' % a: 0 })
  1758.                 a += 1
  1759.         for d in self.dq:
  1760.             self.__dict__[d.replace('-', '_')] = self.dq[d]
  1761.         
  1762.         self.last_event = Event(self.device_uri, '', status_code, prop.username, 0, '', time.time())
  1763.         log.debug(self.dq)
  1764.  
  1765.     
  1766.     def isBusyOrInErrorState(self):
  1767.         
  1768.         try:
  1769.             self.queryDevice(quick = True)
  1770.         except Error:
  1771.             return True
  1772.  
  1773.         return self.error_state in (ERROR_STATE_ERROR, ERROR_STATE_BUSY)
  1774.  
  1775.     
  1776.     def isIdleAndNoError(self):
  1777.         
  1778.         try:
  1779.             self.queryDevice(quick = True)
  1780.         except Error:
  1781.             return False
  1782.  
  1783.         return self.error_state not in (ERROR_STATE_ERROR, ERROR_STATE_BUSY)
  1784.  
  1785.     
  1786.     def getPML(self, oid, desired_int_size = pml.INT_SIZE_INT):
  1787.         channel_id = self.openPML()
  1788.         (result_code, data, typ, pml_result_code) = hpmudext.get_pml(self.device_id, channel_id, pml.PMLToSNMP(oid[0]), oid[1])
  1789.         if pml_result_code > pml.ERROR_MAX_OK:
  1790.             log.debug('PML/SNMP GET %s failed (result code = 0x%x)' % (oid[0], pml_result_code))
  1791.             return (pml_result_code, None)
  1792.         converted_data = pml.ConvertFromPMLDataFormat(data, oid[1], desired_int_size)
  1793.         if log.is_debug():
  1794.             if oid[1] in (pml.TYPE_STRING, pml.TYPE_BINARY):
  1795.                 log.debug('PML/SNMP GET %s (result code = 0x%x) returned:' % (oid[0], pml_result_code))
  1796.                 log.log_data(data)
  1797.             else:
  1798.                 log.debug('PML/SNMP GET %s (result code = 0x%x) returned: %s' % (oid[0], pml_result_code, repr(converted_data)))
  1799.         
  1800.         return (pml_result_code, converted_data)
  1801.  
  1802.     
  1803.     def setPML(self, oid, value):
  1804.         channel_id = self.openPML()
  1805.         value = pml.ConvertToPMLDataFormat(value, oid[1])
  1806.         (result_code, pml_result_code) = hpmudext.set_pml(self.device_id, channel_id, pml.PMLToSNMP(oid[0]), oid[1], value)
  1807.         if log.is_debug():
  1808.             if oid[1] in (pml.TYPE_STRING, pml.TYPE_BINARY):
  1809.                 log.debug('PML/SNMP SET %s (result code = 0x%x) to:' % (oid[0], pml_result_code))
  1810.                 log.log_data(value)
  1811.             else:
  1812.                 log.debug('PML/SNMP SET %s (result code = 0x%x) to: %s' % (oid[0], pml_result_code, repr(value)))
  1813.         
  1814.         return pml_result_code
  1815.  
  1816.     
  1817.     def getDynamicCounter(self, counter, convert_to_int = True):
  1818.         dynamic_counters = self.mq.get('status-dynamic-counters', STATUS_DYNAMIC_COUNTERS_NONE)
  1819.         log.debug('Dynamic counters: %d' % dynamic_counters)
  1820.         if dynamic_counters != STATUS_DYNAMIC_COUNTERS_NONE:
  1821.             if dynamic_counters == STATUS_DYNAMIC_COUNTERS_LIDIL_0_5_4:
  1822.                 self.printData(ldl.buildResetPacket(), direct = True)
  1823.                 self.printData(ldl.buildDynamicCountersPacket(counter), direct = True)
  1824.             else:
  1825.                 self.printData(pcl.buildDynamicCounter(counter), direct = True)
  1826.             (value, tries, times_seen, sleepy_time, max_tries) = (0, 0, 0, 0.1, 5)
  1827.             time.sleep(0.1)
  1828.             while True:
  1829.                 if self.callback:
  1830.                     self.callback()
  1831.                 
  1832.                 sleepy_time += 0.1
  1833.                 tries += 1
  1834.                 time.sleep(sleepy_time)
  1835.                 self.getDeviceID()
  1836.                 if 'CTR' in self.deviceID and pat_dynamic_ctr.search(self.raw_deviceID) is not None:
  1837.                     (dev_counter, value) = parseDynamicCounter(self.deviceID['CTR'], convert_to_int)
  1838.                     if counter == dev_counter:
  1839.                         self.printData(pcl.buildDynamicCounter(0), direct = True)
  1840.                         if not convert_to_int:
  1841.                             value = '#' + value
  1842.                         
  1843.                         return value
  1844.                 
  1845.                 if tries > max_tries:
  1846.                     if dynamic_counters == STATUS_DYNAMIC_COUNTERS_LIDIL_0_5_4:
  1847.                         self.printData(ldl.buildResetPacket())
  1848.                         self.printData(ldl.buildDynamicCountersPacket(counter), direct = True)
  1849.                     else:
  1850.                         self.printData(pcl.buildDynamicCounter(0), direct = True)
  1851.                     return None
  1852.                 if dynamic_counters == STATUS_DYNAMIC_COUNTERS_LIDIL_0_5_4:
  1853.                     self.printData(ldl.buildResetPacket())
  1854.                     self.printData(ldl.buildDynamicCountersPacket(counter), direct = True)
  1855.                     continue
  1856.                 tries > max_tries
  1857.                 self.printData(pcl.buildDynamicCounter(counter), direct = True)
  1858.         else:
  1859.             raise Error(ERROR_DEVICE_DOES_NOT_SUPPORT_OPERATION)
  1860.         return dynamic_counters != STATUS_DYNAMIC_COUNTERS_NONE
  1861.  
  1862.     
  1863.     def readPrint(self, bytes_to_read, stream = None, timeout = prop.read_timeout, allow_short_read = False):
  1864.         return self._Device__readChannel(self.openPrint, bytes_to_read, stream, timeout, allow_short_read)
  1865.  
  1866.     
  1867.     def readPCard(self, bytes_to_read, stream = None, timeout = prop.read_timeout, allow_short_read = False):
  1868.         return self._Device__readChannel(self.openPCard, bytes_to_read, stream, timeout, allow_short_read)
  1869.  
  1870.     
  1871.     def readFax(self, bytes_to_read, stream = None, timeout = prop.read_timeout, allow_short_read = False):
  1872.         return self._Device__readChannel(self.openFax, bytes_to_read, stream, timeout, allow_short_read)
  1873.  
  1874.     
  1875.     def readCfgUpload(self, bytes_to_read, stream = None, timeout = prop.read_timeout, allow_short_read = False):
  1876.         return self._Device__readChannel(self.openCfgUpload, bytes_to_read, stream, timeout, allow_short_read)
  1877.  
  1878.     
  1879.     def readEWS(self, bytes_to_read, stream = None, timeout = prop.read_timeout, allow_short_read = True):
  1880.         return self._Device__readChannel(self.openEWS, bytes_to_read, stream, timeout, allow_short_read)
  1881.  
  1882.     
  1883.     def readSoapFax(self, bytes_to_read, stream = None, timeout = prop.read_timeout, allow_short_read = True):
  1884.         return self._Device__readChannel(self.openSoapFax, bytes_to_read, stream, timeout, allow_short_read)
  1885.  
  1886.     
  1887.     def readWifiConfig(self, bytes_to_read, stream = None, timeout = prop.read_timeout, allow_short_read = True):
  1888.         return self._Device__readChannel(self.openWifiConfig, bytes_to_read, stream, timeout, allow_short_read)
  1889.  
  1890.     
  1891.     def __readChannel(self, opener, bytes_to_read, stream = None, timeout = prop.read_timeout, allow_short_read = False):
  1892.         channel_id = opener()
  1893.         log.debug('Reading channel %d (device-id=%d, bytes_to_read=%d, allow_short=%s, timeout=%d)...' % (channel_id, self.device_id, bytes_to_read, allow_short_read, timeout))
  1894.         num_bytes = 0
  1895.         if stream is None:
  1896.             buffer = ''
  1897.         
  1898.         while True:
  1899.             (result_code, data) = hpmudext.read_channel(self.device_id, channel_id, bytes_to_read, timeout)
  1900.             log.debug('Result code=%d' % result_code)
  1901.             l = len(data)
  1902.             if result_code == hpmudext.HPMUD_R_IO_TIMEOUT:
  1903.                 log.debug('I/O timeout')
  1904.                 break
  1905.             
  1906.             if result_code != hpmudext.HPMUD_R_OK:
  1907.                 log.error('Channel read error')
  1908.                 raise Error(ERROR_DEVICE_IO_ERROR)
  1909.             result_code != hpmudext.HPMUD_R_OK
  1910.             if not l:
  1911.                 log.debug('End of data')
  1912.                 break
  1913.             
  1914.             if stream is None:
  1915.                 buffer = ''.join([
  1916.                     buffer,
  1917.                     data])
  1918.             else:
  1919.                 stream.write(data)
  1920.             num_bytes += l
  1921.             if self.callback is not None:
  1922.                 self.callback()
  1923.             
  1924.             if num_bytes == bytes_to_read:
  1925.                 log.debug('Full read complete.')
  1926.                 break
  1927.             
  1928.             if allow_short_read and num_bytes < bytes_to_read:
  1929.                 log.debug('Allowed short read of %d of %d bytes complete.' % (num_bytes, bytes_to_read))
  1930.                 break
  1931.                 continue
  1932.         if stream is None:
  1933.             log.debug('Returned %d total bytes in buffer.' % num_bytes)
  1934.             return buffer
  1935.         log.debug('Saved %d total bytes to stream.' % num_bytes)
  1936.         return num_bytes
  1937.  
  1938.     
  1939.     def writePrint(self, data):
  1940.         return self._Device__writeChannel(self.openPrint, data)
  1941.  
  1942.     
  1943.     def writePCard(self, data):
  1944.         return self._Device__writeChannel(self.openPCard, data)
  1945.  
  1946.     
  1947.     def writeFax(self, data):
  1948.         return self._Device__writeChannel(self.openFax, data)
  1949.  
  1950.     
  1951.     def writeEWS(self, data):
  1952.         return self._Device__writeChannel(self.openEWS, data)
  1953.  
  1954.     
  1955.     def writeCfgDownload(self, data):
  1956.         return self._Device__writeChannel(self.openCfgDownload, data)
  1957.  
  1958.     
  1959.     def writeSoapFax(self, data):
  1960.         return self._Device__writeChannel(self.openSoapFax, data)
  1961.  
  1962.     
  1963.     def writeWifiConfig(self, data):
  1964.         return self._Device__writeChannel(self.openWifiConfig, data)
  1965.  
  1966.     
  1967.     def __writeChannel(self, opener, data):
  1968.         channel_id = opener()
  1969.         buffer = data
  1970.         bytes_out = 0
  1971.         total_bytes_to_write = len(data)
  1972.         log.debug('Writing %d bytes to channel %d (device-id=%d)...' % (total_bytes_to_write, channel_id, self.device_id))
  1973.         while len(buffer) > 0:
  1974.             (result_code, bytes_written) = hpmudext.write_channel(self.device_id, channel_id, buffer[:prop.max_message_len])
  1975.             log.debug('Result code=%d' % result_code)
  1976.             if result_code != hpmudext.HPMUD_R_OK:
  1977.                 log.error('Channel write error')
  1978.                 raise Error(ERROR_DEVICE_IO_ERROR)
  1979.             result_code != hpmudext.HPMUD_R_OK
  1980.             buffer = buffer[prop.max_message_len:]
  1981.             bytes_out += bytes_written
  1982.             if self.callback is not None:
  1983.                 self.callback()
  1984.                 continue
  1985.         if total_bytes_to_write != bytes_out:
  1986.             raise Error(ERROR_DEVICE_IO_ERROR)
  1987.         total_bytes_to_write != bytes_out
  1988.         return bytes_out
  1989.  
  1990.     
  1991.     def writeEmbeddedPML(self, oid, value, style = 1, direct = True):
  1992.         if style == 1:
  1993.             func = pcl.buildEmbeddedPML2
  1994.         else:
  1995.             func = pcl.buildEmbeddedPML
  1996.         data = func(pcl.buildPCLCmd('&', 'b', 'W', pml.buildEmbeddedPMLSetPacket(oid[0], value, oid[1])))
  1997.         log.log_data(data)
  1998.         self.printData(data, direct = direct, raw = True)
  1999.  
  2000.     
  2001.     def printGzipFile(self, file_name, printer_name = None, direct = False, raw = True, remove = False):
  2002.         return self.printFile(file_name, printer_name, direct, raw, remove)
  2003.  
  2004.     
  2005.     def printParsedGzipPostscript(self, print_file, printer_name = None):
  2006.         
  2007.         try:
  2008.             os.stat(print_file)
  2009.         except OSError:
  2010.             log.error('File not found: %s' % print_file)
  2011.             return None
  2012.  
  2013.         (temp_file_fd, temp_file_name) = utils.make_temp_file()
  2014.         f = gzip.open(print_file, 'r')
  2015.         x = f.readline()
  2016.         while not x.startswith('%PY_BEGIN'):
  2017.             os.write(temp_file_fd, x)
  2018.             x = f.readline()
  2019.         sub_lines = []
  2020.         x = f.readline()
  2021.         while not x.startswith('%PY_END'):
  2022.             sub_lines.append(x)
  2023.             x = f.readline()
  2024.         SUBS = {
  2025.             'VERSION': prop.version,
  2026.             'MODEL': self.model_ui,
  2027.             'URI': self.device_uri,
  2028.             'BUS': self.bus,
  2029.             'SERIAL': self.serial,
  2030.             'IP': self.host,
  2031.             'PORT': self.port,
  2032.             'DEVNODE': self.dev_file }
  2033.         if self.bus == 'net':
  2034.             SUBS['DEVNODE'] = 'n/a'
  2035.         else:
  2036.             SUBS['IP'] = 'n/a'
  2037.             SUBS['PORT'] = 'n/a'
  2038.         for s in sub_lines:
  2039.             os.write(temp_file_fd, s % SUBS)
  2040.         
  2041.         os.write(temp_file_fd, f.read())
  2042.         f.close()
  2043.         os.close(temp_file_fd)
  2044.         self.printFile(temp_file_name, printer_name, direct = False, raw = False, remove = True)
  2045.  
  2046.     
  2047.     def printFile(self, file_name, printer_name = None, direct = False, raw = True, remove = False):
  2048.         is_gzip = os.path.splitext(file_name)[-1].lower() == '.gz'
  2049.         if printer_name is None:
  2050.             printer_name = self.first_cups_printer
  2051.             if not printer_name:
  2052.                 raise Error(ERROR_NO_CUPS_QUEUE_FOUND_FOR_DEVICE)
  2053.             printer_name
  2054.         
  2055.         log.debug("Printing file '%s' to queue '%s' (gzip=%s, direct=%s, raw=%s, remove=%s)" % (file_name, printer_name, is_gzip, direct, raw, remove))
  2056.         if direct:
  2057.             if is_gzip:
  2058.                 self.writePrint(gzip.open(file_name, 'r').read())
  2059.             else:
  2060.                 self.writePrint(file(file_name, 'r').read())
  2061.         elif not utils.which('lpr'):
  2062.             lp_opt = ''
  2063.             if raw:
  2064.                 lp_opt = '-oraw'
  2065.             
  2066.             if is_gzip:
  2067.                 c = 'gunzip -c %s | lp -c -d%s %s' % (file_name, printer_name, lp_opt)
  2068.             else:
  2069.                 c = 'lp -c -d%s %s %s' % (printer_name, lp_opt, file_name)
  2070.             log.debug(c)
  2071.             exit_code = os.system(c)
  2072.             if exit_code != 0:
  2073.                 log.error('Print command failed with exit code %d!' % exit_code)
  2074.             
  2075.             if remove:
  2076.                 os.remove(file_name)
  2077.             
  2078.         else:
  2079.             (raw_str, rem_str) = ('', '')
  2080.             if raw:
  2081.                 raw_str = '-o raw'
  2082.             
  2083.             if remove:
  2084.                 rem_str = '-r'
  2085.             
  2086.             if is_gzip:
  2087.                 c = 'gunzip -c %s | lpr %s %s -P%s' % (file_name, raw_str, rem_str, printer_name)
  2088.             else:
  2089.                 c = 'lpr -P%s %s %s %s' % (printer_name, raw_str, rem_str, file_name)
  2090.             log.debug(c)
  2091.             exit_code = os.system(c)
  2092.             if exit_code != 0:
  2093.                 log.error('Print command failed with exit code %d!' % exit_code)
  2094.             
  2095.  
  2096.     
  2097.     def printTestPage(self, printer_name = None):
  2098.         return self.printParsedGzipPostscript(os.path.join(prop.home_dir, 'data', 'ps', 'testpage.ps.gz'), printer_name)
  2099.  
  2100.     
  2101.     def printData(self, data, printer_name = None, direct = True, raw = True):
  2102.         if direct:
  2103.             self.writePrint(data)
  2104.         else:
  2105.             (temp_file_fd, temp_file_name) = utils.make_temp_file()
  2106.             os.write(temp_file_fd, data)
  2107.             os.close(temp_file_fd)
  2108.             self.printFile(temp_file_name, printer_name, False, raw, remove = True)
  2109.  
  2110.     
  2111.     def cancelJob(self, jobid):
  2112.         cups.cancelJob(jobid)
  2113.         self.error_code = STATUS_PRINTER_CANCELING
  2114.         self.sendEvent(self.error_code)
  2115.  
  2116.     
  2117.     def queryHistory(self):
  2118.         result = []
  2119.         if self.dbus_avail:
  2120.             
  2121.             try:
  2122.                 (device_uri, history) = self.service.GetHistory(self.device_uri)
  2123.             except dbus.exceptions.DBusException:
  2124.                 e = None
  2125.                 log.error('dbus call to GetHistory() failed.')
  2126.                 return []
  2127.  
  2128.             history.reverse()
  2129.             for h in history:
  2130.                 result.append(Event(*tuple(h)))
  2131.             
  2132.             
  2133.             try:
  2134.                 self.error_code = result[0].event_code
  2135.             except IndexError:
  2136.                 self.error_code = STATUS_UNKNOWN
  2137.  
  2138.             self.error_state = STATUS_TO_ERROR_STATE_MAP.get(self.error_code, ERROR_STATE_CLEAR)
  2139.         else:
  2140.             self.error_code = STATUS_UNKNOWN
  2141.             self.error_state = ERROR_STATE_CLEAR
  2142.         self.hist = result
  2143.         return result
  2144.  
  2145.     
  2146.     def getEWSUrl(self, url, stream):
  2147.         
  2148.         try:
  2149.             if self.is_local:
  2150.                 url2 = '%s&loc=%s' % (self.device_uri.replace('hpfax:', 'hp:'), url)
  2151.                 data = self
  2152.             else:
  2153.                 url2 = 'http://%s%s' % (self.host, url)
  2154.                 if self.zc:
  2155.                     (status, ip) = hpmudext.get_zc_ip_address(self.zc)
  2156.                     if status == hpmudext.HPMUD_R_OK:
  2157.                         url2 = 'http://%s%s' % (ip, url)
  2158.                     
  2159.                 
  2160.                 data = None
  2161.             log.debug('Opening: %s' % url2)
  2162.             opener = LocalOpener({ })
  2163.             
  2164.             try:
  2165.                 f = opener.open(url2, data)
  2166.             except Error:
  2167.                 log.error('Status read failed: %s' % url2)
  2168.                 stream.seek(0)
  2169.                 stream.truncate()
  2170.  
  2171.             
  2172.             try:
  2173.                 stream.write(f.read())
  2174.             finally:
  2175.                 f.close()
  2176.  
  2177.         finally:
  2178.             self.closeEWS()
  2179.  
  2180.  
  2181.     
  2182.     def downloadFirmware(self, usb_bus_id = None, usb_device_id = None):
  2183.         ok = False
  2184.         filename = os.path.join(prop.data_dir, 'firmware', self.model.lower() + '.fw.gz')
  2185.         log.debug(filename)
  2186.         if os.path.exists(filename):
  2187.             log.debug("Downloading firmware file '%s'..." % filename)
  2188.             
  2189.             try:
  2190.                 self.openPrint()
  2191.                 bytes_written = self.writePrint(gzip.open(filename).read())
  2192.                 log.debug('%s bytes downloaded.' % utils.commafy(bytes_written))
  2193.                 self.closePrint()
  2194.                 ok = True
  2195.                 log.debug('OK')
  2196.             except Error:
  2197.                 e = None
  2198.                 log.error('An error occured: %s' % e.msg)
  2199.             except:
  2200.                 None<EXCEPTION MATCH>Error
  2201.             
  2202.  
  2203.         None<EXCEPTION MATCH>Error
  2204.         log.error("Firmware file '%s' not found." % filename)
  2205.         return ok
  2206.  
  2207.  
  2208.  
  2209. class xStringIO(StringIO.StringIO):
  2210.     
  2211.     def makefile(self, x, y):
  2212.         return self
  2213.  
  2214.  
  2215.  
  2216. class LocalOpener(urllib.URLopener):
  2217.     
  2218.     def open_hp(self, url, dev):
  2219.         log.debug('open_hp(%s)' % url)
  2220.         match_obj = http_pat_url.search(url)
  2221.         if not match_obj.group(1):
  2222.             pass
  2223.         bus = ''
  2224.         if not match_obj.group(2):
  2225.             pass
  2226.         model = ''
  2227.         if not match_obj.group(3):
  2228.             pass
  2229.         serial = ''
  2230.         if not match_obj.group(4):
  2231.             pass
  2232.         device = ''
  2233.         if not match_obj.group(5):
  2234.             pass
  2235.         loc = ''
  2236.         dev.openEWS()
  2237.         dev.writeEWS('GET %s HTTP/1.0\nContent-Length:0\nHost:localhost\nUser-Agent:hplip\n\n' % loc)
  2238.         reply = xStringIO()
  2239.         while dev.readEWS(8192, reply, timeout = 1):
  2240.             pass
  2241.         reply.seek(0)
  2242.         log.log_data(reply.getvalue())
  2243.         response = httplib.HTTPResponse(reply)
  2244.         response.begin()
  2245.         if response.status != httplib.OK:
  2246.             raise Error(ERROR_DEVICE_STATUS_NOT_AVAILABLE)
  2247.         response.status != httplib.OK
  2248.         return response.fp
  2249.  
  2250.  
  2251.